package finbudget.client.ui.table.fields;

import finbudget.client.ui.table.Field;
import finbudget.client.ui.table.Record;
import finbudget.client.ui.table.Transformator;
import finbudget.client.ui.widget.upload.Attachment;
import finbudget.shared.Constants;

public class AttachmentField extends Field {
	private static final long serialVersionUID = 3730785360459257449L;

	/**
	 * Optional field Id that stores node's key associated with the Attachment field.
	 * In case this field is null then Attachment.keyNodeId is used.
	 */
	private String attachmentNodeFieldId;
	/**
	 * Optional node's key associated with the Attachment field.
	 */
	private String attachmentNodeKey;

	/** serialization requirements */
	protected AttachmentField() {
		super();
	}

	public AttachmentField(String id, String name, int row, int col) {
		super();

		this.id = id;
		this.captionForm = this.captionGrid = name;
		this.row = row;
		this.column = col;
		this.type = Type.ATTACHMENT;
	}

	public String getAttachmentNodeFieldId() {
		return attachmentNodeFieldId == null ? Attachment.keyNodeId : attachmentNodeFieldId;
	}

	// TODO Before thoroughly tested don't use it... For tests it's worth to change Attachment.keyNodeId name
	public AttachmentField setAttachmentNodeFieldId(String attachmentNodeFieldId) {
		this.attachmentNodeFieldId = attachmentNodeFieldId;
		return this;
	}

	public static String getAttachmentNodeKey(Field field, Record record) {
		if (field != null) {
			String fieldId;
			if (field instanceof AttachmentField) {
				if (((AttachmentField) field).attachmentNodeKey != null) {
					return ((AttachmentField) field).attachmentNodeKey;
				}
				fieldId = ((AttachmentField) field).getAttachmentNodeFieldId();
			} else {
				fieldId = Attachment.keyNodeId;
			}
			if (record != null) {
				return record.getValueString(fieldId);
			}
		}
		return Constants.fakeNodeKeyForAttachments;
	}

	public String getAttachmentNodeKey() {
		return attachmentNodeKey;
	}

	public AttachmentField setAttachmentNodeKey(String attachmentNodeKey) {
		this.attachmentNodeKey = attachmentNodeKey;
		return this;
	}

	@Override
	public Object toRaw(Transformator transformator, Object value) {
		return transformator.toRaw(this, value);
	}

	@Override
	public String fromRaw(Transformator transformator, Object value) {
		return transformator.fromRaw(this, value);
	}

}
